package com.jingyanzi.resallocation.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.jingyanzi.resallocation.service.IAreaService;
import com.jingyanzi.resallocation.service.IAssistantService;
import com.jingyanzi.resallocation.service.IClubService;
import com.jingyanzi.resallocation.service.ISalesGroupService;
import com.jingyanzi.resallocation.service.ISampleService;
import com.jingyanzi.resallocation.service.IStoreService;

public class ResFactory {
	private static AtomicBoolean isInit = new AtomicBoolean(false);
	
	private static ApplicationContext context = null;
	
	private static AtomicBoolean isTest = new AtomicBoolean(false);
	
	public static void initCofing() {
		Properties properties = new Properties();
		InputStream in = ResFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String value = properties.getProperty("run.test");
		if(value.equals("on")) {
			isTest.set(true);
		}
		if (!isInit.get()) {
			if(isTest.get()) {
				context = new FileSystemXmlApplicationContext(
						"classpath:resallocation-test-application.xml");
				System.out.println("init test application.xml");
			} else {
				context = new FileSystemXmlApplicationContext(
						"classpath:resallocation-application.xml");
				System.out.println("init application.xml");
			}
			isInit.set(true);
		}	
	}
	
	
	public static IAssistantService getAssistantService() {
		initCofing();
		IAssistantService assistantService = (IAssistantService) context.getBean("assistantService");
		return assistantService;
	}
	
	public static IAreaService getAreaService() {
		initCofing();
		IAreaService areaService = (IAreaService) context.getBean("areaService");
		return areaService;
	}
	
	public static IClubService getClubService() {
		initCofing();
		IClubService clubService = (IClubService) context.getBean("clubService");
		return clubService;
	}
	
	public static ISalesGroupService getSalesGroupService() {
		initCofing();
		ISalesGroupService salesGroupService = (ISalesGroupService) context.getBean("salesGroupService");
		return salesGroupService;
	}
	
	public static ISampleService getSampleService() {
		initCofing();	
		ISampleService sampleService = (ISampleService) context.getBean("sampleService");
		return sampleService;
	}
	
	public static IStoreService getStoreService() {
		initCofing();
		IStoreService storeService = (IStoreService) context.getBean("storeService");
		return storeService;
	}
}
